package com.example.exchangeapp.yy.fragment;

import static com.example.exchangeapp.yy.utils.AlertDialogUtils.mOnDialogButtonClickListener;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.exchangeapp.MainActivity;
import com.example.exchangeapp.R;
import com.example.exchangeapp.yy.constant.UserLogin;
import com.example.exchangeapp.yy.entity.GoodVo2;
import com.example.exchangeapp.yy.entity.Goods;
import com.example.exchangeapp.yy.request.HttpRequestUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class DialogAddGoods extends AppCompatActivity {
   public static Map<String,Integer> type_id_maps =new HashMap<>();
    private Button choose_photo;
    private Button btn_camera;
    private ImageView imageView;
    private String imagePath;
    public static Goods goods =new Goods();
    public static volatile String msg ="失败";

    public static final int TAKE_CAMERA = 101;
    public static final int PICK_PHOTO = 102;
    private Uri imageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_add_goods);
      initSpinner();
      initImage();
    }


    //初始化下拉列表数据
    public void initSpinner(){
        //设置下拉列表
        Spinner spinner = findViewById(R.id.spinner_location);
        String[] strings = type_id_maps.keySet().toArray(new String[0]);

        ArrayAdapter<String> adapter2=new ArrayAdapter<String>(DialogAddGoods.this,android.R.layout.simple_spinner_item ,strings);
        spinner.setAdapter(adapter2);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //设置商品的类型id
                goods.setTypeId(type_id_maps.get(strings[position]));
                //设置商品的类型名称
                goods.setTypeName(strings[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //设置取消按钮点击事件
        findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //为确认按钮设置点击监听
        findViewById(R.id.comfirm_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText  googs_content = (EditText)findViewById(R.id.googs_content);
                EditText  goods_price = (EditText)findViewById(R.id.goods_price);
                EditText  sell_addr = (EditText)findViewById(R.id.sell_addr);

                if (googs_content.getText().toString().equals("")){
                  Toast.makeText(DialogAddGoods.this,"请输入商品描述",Toast.LENGTH_LONG).show();

                }else if (goods_price.getText().toString().equals("")){
                    Toast.makeText(DialogAddGoods.this,"请输入商品单价",Toast.LENGTH_LONG).show();

                }else if (sell_addr.getText().toString().equals("")){
                    Toast.makeText(DialogAddGoods.this,"请输入卖家地址",Toast.LENGTH_LONG).show();
                }else if (imagePath==null){
                    Toast.makeText(DialogAddGoods.this,"请选择图片",Toast.LENGTH_LONG).show();

                }else{
                    goods.setUserId(UserLogin.uid);
                    goods.setAddr(sell_addr.getText().toString());
                    goods.setPrice(Integer.valueOf(goods_price.getText().toString()));
                    goods.setContent(googs_content.getText().toString());
                    //都先通过上传图片
                    HttpRequestUtils.postImage(new File(imagePath));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //这时goods的ImageCode会被赋值
                  HttpRequestUtils.postGoos(goods);
                    try {
                        //睡眠一会
                      Thread.sleep(500);

                        if (HasSendGoods.msg.equals("成功")){
                            //重新设置为失败
                            HasSendGoods.msg = "失败";
                            GoodVo2 goodVo2 = new GoodVo2();

                            goodVo2.setImageUrlList(HasSendGoods.imageList);
                            goodVo2.setAddr(goods.getAddr());
                            goodVo2.setContent(goods.getContent());
                            goodVo2.setPrice(goods.getPrice());
                            goodVo2.setTypeName(goods.getTypeName());
                            goodVo2.setId(HasSendGoods.index+"");
                            HasSendGoods.data.add(goodVo2);

                            Toast.makeText(DialogAddGoods.this,"发布成功",Toast.LENGTH_LONG).show();
                            HasSendGoods.num++;
                            finish();
                        }else{
                            Toast.makeText(DialogAddGoods.this,"发布失败",Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    //初始化选择图片的相关事件
    public void initImage(){
      imageView = (ImageView) findViewById(R.id.image_show);
      imageView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              //动态申请获取访问 读写磁盘的权限
              if (ContextCompat.checkSelfPermission(DialogAddGoods.this,
                      Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                  ActivityCompat.requestPermissions(DialogAddGoods.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
              } else {
                  //打开相册
                  Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                  //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                  intent.setType("image/*");
                  startActivityForResult(intent, PICK_PHOTO); // 打开相册
              }
          }
      });


  }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_CAMERA:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        imageView.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PICK_PHOTO:
                if (resultCode == RESULT_OK) { // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        System.out.println("4.4及以上系统使用这个方法处理图片");
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }

                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath);
    }

    /**
     * android 4.4以前的处理方式
     * @param data
     */
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            this.imagePath = imagePath;
            imageView.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
        }
    }
}